import 'dart:async';
import 'dart:collection';
import 'package:rxdart/rxdart.dart';

import 'package:like_chat/blocs/bloc_provider.dart';
import 'package:like_chat/dto/history_chat.dart';

class HistoryChatBloc implements BlocBase {
  List<HistoryChatModel> _list;

  StreamController<List<HistoryChatModel>> _syncController =
      BehaviorSubject<List<HistoryChatModel>>();

  Stream<List<HistoryChatModel>> get outHistoryChatStream =>
      _syncController.stream;

  HistoryChatBloc() {
    _list = [];
    Future.delayed(Duration(seconds: 3), () {
      add(HistoryChatModel(
        name: "张三",
        lastMsg: "吃了？",
        lastTime: "10:20",
        unreadNum: 0,
        friendId: "10001"
      ));
      add(HistoryChatModel(
          name: "里斯",
          lastMsg: "我已经在学习了",
          lastTime: "10:30",
          unreadNum: 1,
          friendId: "10002"
      ));
    });
    Future.delayed(Duration(seconds: 5), () {
      update(HistoryChatModel(
          name: "张三",
          lastMsg: "吃了？",
          lastTime: "10:20",
          unreadNum: 3,
          friendId: "10001"
      ));
    });
  }

  void add(HistoryChatModel h) {
    _list.add(h);
    _syncController.sink.add(UnmodifiableListView(_list));
  }

  void addAll(List<HistoryChatModel> lists) {
    _list.addAll(lists);
    _syncController.sink.add(UnmodifiableListView(_list));
  }

  void update(HistoryChatModel h) {
    var _newList = _list.where((h1) => h1.friendId != h.friendId).toList();
    _list.clear();
    _newList.insert(0, h);
    _list.addAll(_newList);
    _syncController.sink.add(UnmodifiableListView(_list));
  }

  @override
  void dispose() {
    _syncController.close();
  }
}
